//TreeSetTest3.java
package com.ylaihui.setitf;

import java.util.Objects;
import java.util.TreeSet;

class Phone implements Comparable{
    String name;
    double price;

    public Phone(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Phone phone = (Phone) o;
        return Double.compare(phone.price, price) == 0 &&
                Objects.equals(name, phone.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }

    public Phone() {
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof Phone){
            Phone p = (Phone) o;
            // name 从大到小排序
            int ret = -this.name.compareTo(((Phone) o).name);
            if(ret == 0)
                // price 从小到大排序
                return Double.compare(this.price,((Phone) o).price);
            else
                return ret;

        }else
            throw new RuntimeException("无法比较的类型");
    }
}

public class TreeSetTest3 {
    public static void main(String[] args) {
        TreeSet set = new TreeSet();
        set.add(new Phone("huawei",4288));
        set.add(new Phone("huawei",1288));
        set.add(new Phone("iPhone",5288));
        set.add(new Phone("mi",1288));
        // 如果重写的compareTo 方法只比较的name
        // 那么下面的两条数据只能插入第一条，因为name相等，
        // TreeSet底层判断这两个对象是相等的 compareTo 返回0
        set.add(new Phone("vivo",1288));
        set.add(new Phone("vivo",2288));

        for (Object obj : set) {
            System.out.println(obj);
        }
    }
}
/*
Phone{name='vivo', price=1288.0}
Phone{name='vivo', price=2288.0}
Phone{name='mi', price=1288.0}
Phone{name='iPhone', price=5288.0}
Phone{name='huawei', price=1288.0}
Phone{name='huawei', price=4288.0}
 */
